package dongshi.daddy.huohuo;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.IntStream;

public class LoopCounter {
    public static void main(String[] args) {
        int loopNum = 100_0000;
        LoopCounter loopCounter = new LoopCounter();
        IntStream.range(0, loopNum).parallel().forEach(i -> loopCounter.addAndGet());
        System.out.println("sum 最终：" + loopCounter.getSum());
    }

    private int sum = 0;
    // 1：可重入 ReentrantLock
    // 2：公平锁 true
    private Lock lock = new ReentrantLock(true);
    public int addAndGet() {
        try {
            lock.lock();
            return ++sum;
        } finally {
            lock.unlock();
        }
    }

    public int getSum() {
        return sum;
    }
}
